package cn.hengzhu.main_manager.utils.aop;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.hengzhu.main_manager.repository.dao.OperationLogRecordMapper;
import cn.hengzhu.main_manager.repository.domain.ManageUser;
import cn.hengzhu.main_manager.repository.domain.OperationLogRecord;
import cn.hengzhu.main_manager.utils.IpAdrrUtil;
import cn.hengzhu.main_manager.utils.UserContext;
import cn.hengzhu.main_manager.utils.ann.SystemControllerLog;

@Aspect
@Component
public class LogByAop {

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private OperationLogRecordMapper operationLogRecordMapper;

	/**
	 * Controller层切点 注解拦截
	 */
	// @Pointcut("@annotation(cn.hengzhu.main_manager.utils.ann.SystemControllerLog)")
	// public void controllerAspect(){}

	/**
	 * 后置通知 用于拦截Controller层记录用户的操作
	 * 
	 * @param joinPoint
	 *            切点
	 */
	@After("@annotation(systemControllerLog)")
	public void doAfter(JoinPoint joinPoint, SystemControllerLog systemControllerLog) {
		boolean useKey = systemControllerLog.useKey();
		String userName = "";
		Map<String, String[]> params = request.getParameterMap();
		if (useKey) {
			String[] strings = params.get(useKey);
			userName = strings[0];
		} else {
			ManageUser user = UserContext.getUser();
			if (null != user) {
				userName = user.getLoginName();
			} else {
				userName = (String) request.getSession().getAttribute("fromUserName");
			}
			String title = systemControllerLog.description();
			String remoteAddr = IpAdrrUtil.getClientIpAddr(request);// 请求的IP
			String requestUrl = request.getRequestURL().toString();
			String method = request.getMethod();

			OperationLogRecord log = new OperationLogRecord();
			log.setUserName(userName);
			log.setTitle(title);
			log.setMethod(method);
			log.setIp(remoteAddr);
			log.setUrl(requestUrl);
			log.setParams(setMapToParams(params));
			log.setCreatTime(new Date());

			operationLogRecordMapper.insertSelective(log);

		}

	}

	public String setMapToParams(Map<String, String[]> paramMap) {
		if (paramMap == null) {
			return "";
		}
		StringBuilder params = new StringBuilder();
		for (Map.Entry<String, String[]> param : ((Map<String, String[]>) paramMap).entrySet()) {
			params.append(("".equals(params.toString()) ? "" : "&") + param.getKey() + "=");
			String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");
			params.append(paramValue);
		}
		return params.toString();
	}

}
